﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Dev.Control;
using SfcorpDLL.ety;
using SfcorpDLL.biz;
using TT.Common;
using TT.ORM;
using Billing.ety;
using Billing;
using GT.ORM;
using Dev.Control.Form;
using GT.ReportDLL.Biz;
using GT.ReportDLL.ety;
using System.Collections;
using DevExpress.XtraGrid.Views.Base;
using DevExpress.Utils;

namespace Sfcorp.form
{
    public partial class frmAgyBns : BaseFormDev
    {
        bizAgyBns bzAgyBns;
        FactoryBill bzBill;
        etyBillParams eyBillRq = new etyBillParams();
        bool isBilled = false;
        etyBillParams eyBllPara = new etyBillParams();
        etyFrtAgyBns eyBnsHdr = new etyFrtAgyBns();
        IList<etyChargeDtl> ilChrg = new List<etyChargeDtl>();
        IList<etyFrtAgyBns> ilAnyBnsDtl = new List<etyFrtAgyBns>();        //业务单明细

        IList<etyFrtAgyBns> ilImageList = new List<etyFrtAgyBns>();
        IList<etyFrtAgyBns> ilAddImgList = new List<etyFrtAgyBns>();
        IList<etyFrtAgyBns> ilDelImgList = new List<etyFrtAgyBns>();
        //public string ContractNo = "DK1505010013";// "DK--201504--0008";
        public string ContractNo = string.Empty;

        //IList<etyChargeDtl> ilModifyBill = new List<etyChargeDtl>();//记录修改过的费用列表
        //IList<etyChargeDtl> ilDeleteBill = new List<etyChargeDtl>();//记录删除过的费用列表
        //IList<etyChargeDtl> ilCreateBill = new List<etyChargeDtl>();//记录过的费用列表

        public frmAgyBns()
        {
            InitializeComponent();
            InitSubButton();
        }

        #region 子工具栏处理
        private void InitSubButton()
        {
            //业务办单
            ctrAgyBns1.barCreate.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(barCreate_ItemClick);
            ctrAgyBns1.barLock.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(barLock_ItemClick);
            ctrAgyBns1.barDelete.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(barDelete_ItemClick);
            //计费
            ctrAgyBns2.barBillAdd.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(barBillAdd_ItemClick);
            ctrAgyBns2.barBillDel.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(barBillDel_ItemClick);
            ctrAgyBns2.barBillEdit.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(barBillEdit_ItemClick);
            ctrAgyBns2.barBillTY.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(barBillTY_ItemClick);
            //图片
            ctrAgyBns3.barImgAdd.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(barImgAdd_ItemClick);
            ctrAgyBns3.barImgDel.ItemClick += new DevExpress.XtraBars.ItemClickEventHandler(barImgDel_ItemClick);
        }

        //业务
        void barLock_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //ggcDocList.gridView.OptionsBehavior.Editable = false;
            if (ctrAgyBns1.barLock.ImageIndex == 2)     //锁定
            {
                ctrAgyBns1.barLock.ImageIndex = 3;
                ctrAgyBns1.barLock.Caption = "开锁";
                gvBns.OptionsBehavior.Editable = true;
            }
            else//非锁定
            {
                ctrAgyBns1.barLock.ImageIndex = 2;
                ctrAgyBns1.barLock.Caption = "锁定";
                gvBns.OptionsBehavior.Editable = false;
            }
        }
        void barDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            etyFrtAgyBns ey = srcBinding.Current as etyFrtAgyBns;
            if (ey == null)
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("请先选择列表中的记录来删除");
                return;
            }
            if (FormSta == "E")//编辑模式下，删除时，要把对象保存起来，当点保存按钮时要删除数据库中的记录
            {
                ey.CANCEL_NAM = global.basSysPara.UserID;
                delFabConList.Add(ey);
            }
            srcBinding.RemoveCurrent();
            SumCountContainer();
        }
        void barCreate_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            F6();
        }

        //计费
        void barBillAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowGetMoney(true);
            return;

            etyChargeDtl eyBill = srcBill.Current as etyChargeDtl;
            if (eyBill == null)
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("请先选择列表中的记录");
                return;
            }
            frmAgyBnsBillAddNew fmBillItem = new frmAgyBnsBillAddNew(bzAgyBns, eyBill,DataProcType.NEW);
            //if (fmBillItem.ShowDialog() == DialogResult.OK)
            //{
            //    gvBill.GroupCount = 0;
            //    //IList<etyChargeDtl> srcBillList = srcBill.DataSource as IList<etyChargeDtl>;
            //    //srcBillList.Add(fmBillItem.BillItem);
            //    ilChrg.Add(fmBillItem.eyChrgDtl);
            //    srcBill.DataSource = ilChrg;
            //    ggcBilling.DataSource = srcBill;
            //    ggcBilling.GridView.ClearSelection();

            //    gvBill.GroupCount = 1;
            //    gvBill.ExpandAllGroups();
            //    ggcBilling.AutoColumnWidth();

            //    //ilCreateBill.Add(eyBill);
            //}
        }
        void barBillDel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowGetMoney(true);
            return;

            //etyChargeDtl eyBillI = srcBill.Current as etyChargeDtl;
            //etyChargeDtl eyBillO = srcBillO.Current as etyChargeDtl;
            //if (eyBillI == null && eyBillO == null)
            //{
            //    TT.HelpInfo.MsgBox.ShowWarnBox("请先选择列表中的记录来删除");
            //    return;
            //}
            //if (eyBillI != null)
            //    srcBill.RemoveCurrent();
            //if (eyBillO != null)
            //    srcBillO.RemoveCurrent();
            etyChargeDtl eyBill = srcBill.Current as etyChargeDtl;
            if (eyBill == null)
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("请先选择列表中的记录来删除");
                return;
            }
            if (eyBill != null)
            {
                srcBill.RemoveCurrent();
                //if (ilCreateBill.Contains(eyBill))
                //    ilCreateBill.Remove(eyBill);
                //else if (ilModifyBill.Contains(eyBill))
                //    ilModifyBill.Remove(eyBill);
                //ilDeleteBill.Add(eyBill);
            }
        }
        void barBillEdit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            ShowGetMoney(true);
        }
        void barBillTY_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //mstShow  是否强行显示
            if (Convert.ToDouble(txtCash.EditValue) > 0 && ilChrg.Count > 0)
            {
                eyBillRq.BILL_KEY1 = eyBnsHdr.FABC_GKEY;
                eyBillRq.BILL_KEY2 = eyBnsHdr.CONTRACT_NO;
                eyBillRq.CUSTOMER = eyBnsHdr.CUSTOMER_ID;

                ilChrg[0].QTY = ilAnyBnsDtl.Count.ToString().Trim();
                frmAgyBnsTY fmBill = new frmAgyBnsTY(ilChrg[0], eyBillRq, type_view_bill.bnsCash, null, bzBill);
                fmBill.ShowDialog();
                Billing(false);
            }
            else
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("未产生计费结果，或全部费用为月结，不允许添加费用。");
            }
        }

        //图片
        void barImgAdd_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            //为对话框设置标题
            ofd.Title = "请选择图片";
            //设置筛选的图片格式
            ofd.Filter = "图片格式|*.jpg;*.png;*.jpeg;*.bmp;*.gif";
            //ofd.Filter = "(*.jpg,*.png,*.jpeg,*.bmp,*.gif)|*.jgp;*.png;*.jgp;*.jpeg;*.bmp;*.gif|All files(*.*)|*.*";
            //ofd.Filter = "图片|*.*";
            //设置是否允许多选
            ofd.Multiselect = true;

            if (ofd.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                return;
            srcImage.DataSource = new List<etyFrtAgyBns>();//必须取消和网格的绑定，才能改变数据源，不然获取选中行时会出错
            //获得文件的完整路径（包括名字后后缀）
            string[] filePaths = ofd.FileNames;
            foreach (string filePath in filePaths)
            {
                byte[] bImage = TT.Common.ImageProcess.getImageByte(filePath);
                etyFrtAgyBns eyImage = new etyFrtAgyBns();
                eyImage.FILE_NAME = System.IO.Path.GetFileName(filePath);
                eyImage.BNS_IMG_SAVE = bImage;
                ilImageList.Add(eyImage);
                if (FormSta == "E") //编辑模式下追加图片，要保存起来
                    ilAddImgList.Add(eyImage);
            }
            srcImage.DataSource = ilImageList;
            ggcImageList.DataSource = srcImage;
            ggcImageList.AutoColumnWidth();

            //JustMe 20150605暂时统一保存里做，不单独保存
            if (FormSta == "E")//编辑模式添加图片后自动保存
            {
                //SaveDate();
                try
                {
                    splashScreenManager1.ShowWaitForm();
                }
                catch { }
                foreach (etyFrtAgyBns eyImage in ilAddImgList)
                {
                    eyImage.CONTRACT_NO = eyBnsHdr.CONTRACT_NO;
                    if (!bzAgyBns.BnsImageInsert(eyImage))
                    {
                        TT.HelpInfo.MsgBox.ShowWarnBox("图片：" + eyImage.FILE_NAME + "保存失败");
                    }
                }
                ilAddImgList.Clear();
                etyFrtAgyBns ey = new etyFrtAgyBns();
                ey.CONTRACT_NO = txtContract_No.Text.Trim();
                GetBnsImgs(ey);
                try { splashScreenManager1.CloseWaitForm(); }
                catch { }
            }
        }
        void barImgDel_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            etyFrtAgyBns ey = srcImage.Current as etyFrtAgyBns;
            if (ey == null)
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("请先选择列表中的记录来删除");
                return;
            }
            srcImage.RemoveCurrent();
            if (FormSta == "E")
            {
                if (ilAddImgList.Contains(ey))
                    ilAddImgList.Remove(ey);
                else
                    ilDelImgList.Add(ey);
                //直接删除
                foreach (etyFrtAgyBns eyImage in ilDelImgList)
                {
                    if (!bzAgyBns.BsnImageDele(eyImage))
                    {
                        TT.HelpInfo.MsgBox.ShowWarnBox("图片：" + eyImage.FILE_NAME + "删除失败");
                    }
                }
                ilDelImgList.Clear();
            }
        }

        #endregion 

        private string formSta;
        public string FormSta
        {
            set
            {
                formSta = value;
                delFabConList = new List<etyFrtAgyBns>();
                RemoveDtlControlEvent();
                switch (formSta)
                {
                    case "A":
                        lblBar.Caption = "新建状态";
                        btnDelete.Enabled = false;
                        break;
                    case "E":
                        lblBar.Caption = "编辑状态";
                        btnDelete.Enabled = true;
                        curContractNo = txtContract_No.Text;//保存起正在编辑的业务单号，以防业务单号被修改
                        break;
                    default:
                        break;
                }
            }
            get
            {
                return formSta;
            }
        }
        private string curContractNo;
        DataSet dsComboSource = new DataSet();
        private void frmAgyBns_Load(object sender, EventArgs e)
        {
            //权限处理
            global.bzUser.SetFormSecrity(this, barManager1.Items, new etyUsersModCtrl() { USER_ID = global.basSysPara.UserID, MOD_ID = this.MOD_ID });

            //刷新界面所需要的数据
            TT.Module.RefreshTable.BaseTableRefreshByTables(string.Empty, false);
            bnsStatus = "N";

            string sMapingCols;
            string sMapingHeaderTxt;
            bzAgyBns = new bizAgyBns(global.basSysPara);
            //第一表格
            ggcDtl.GridView = this.gvBns;
            ggcDtl.GridView.OptionsBehavior.EditorShowMode = DevExpress.Utils.EditorShowMode.Click;
            string sGridHead = "[SEA_BILL_NO;海运提单号],[AGENT_BILL_NO;货代提单号],[CNTR;柜号],[BOOKING_NO;SO送单号],[WORK_WAY_NAM;作业方式{0}COMBOBOX],[CNTR_SIZ_COD;尺寸{0}COMBOBOX],[CNTR_TYP_COD;类型{0}COMBOBOX],[FOREIGN_VVD_DESC;内外贸{0}COMBOBOX],[B_WEIGHING;是否过磅{0}CHECKBOX],[BNS_SPC_MOD_DESC;特别处理{0}COMBOBOX],[CARGO_NAM;货物名称],[FLOW_COD;流向港口],[SHIP_NAM;船名],[VOYAGE;航次],[UNDG_NO;国际危规号],[CNTR_CTRL_COD;控箱],[CNTR_OPER_COD;箱属]".Replace("{0}", global.symb);
            //下面的不能去掉，如果不是保存不成功的。
            sGridHead += ",[BNS_SPC_MOD;特别处理],[FOREIGN_VVD;内外贸标识],[WORK_WAY_ID;作业方式]";
            ggcDtl.ColumnsMappingCreate(sGridHead);
            gvBns.OptionsBehavior.Editable = false;
            ggcDtl.ColumnEnabled("SEA_BILL_NO{0}AGENT_BILL_NO{0}CNTR{0}BOOKING_NO{0}WORK_WAY_NAM{0}CNTR_SIZ_COD{0}CNTR_TYP_COD{0}FOREIGN_VVD_DESC{0}B_WEIGHING{0}BNS_SPC_MOD_DESC{0}CARGO_NAM{0}FLOW_COD{0}SHIP_NAM{0}VOYAGE{0}UNDG_NO".Replace("{0}", global.recd), false);
            this.winUtil.LoadGridLayout(ggcDtl);

            #region 表格下拉处理
            try
            {
                //业务类型
                dataProcessor.DataSetAddList<etyCodeRef>(ref dsComboSource,global.ilWorkWay, "WORK_WAY_NAM", "CODE_DESC");
                //内外贸
                dataProcessor.DataSetAddList<etyCodeRef>(ref dsComboSource, global.ilForeignVvd, "FOREIGN_VVD_DESC", "CODE_DESC");
                //特别处理
                dataProcessor.DataSetAddList<etyCodeRef>(ref dsComboSource, global.ilBnsSpcMod, "BNS_SPC_MOD_DESC", "CODE_DESC");
                //尺寸
                dataProcessor.DataSetAddList<etyCodeRef>(ref dsComboSource, global.ilCntrSize, "CNTR_SIZ_COD", "CODE");
                //箱型
                dataProcessor.DataSetAddList<etyCodeRef>(ref dsComboSource, global.ilCntrType, "CNTR_TYP_COD", "CODE");

                ggcDtl.BindComboData(dsComboSource);
            }
            catch            (Exception ex)
            {
                TT.HelpInfo.MsgBox.ShowWarnBox(ex.ToString());
            }
            #endregion 
            //计费单
            ggcBilling.GridView = this.gvBill;
            ggcBilling.GridView.OptionsBehavior.EditorShowMode = DevExpress.Utils.EditorShowMode.Click;
            sMapingCols = "CUSTOMER_NAME,ITEM_DESC,IO_FLAG_DESC,CASH_FLAG_DESC,UNIT_DESC,PRICE,QTY ,AMOUNT,INVOICE_NO,CHRG_DESC2,CHRG_DESC3,CHRG_DESC4,CHRG_DESC5,CHRG_FLT20,CHRG_DESC22  ,CHRG_DESC23,CHRG_FLT24,CHRG_DESC26,CHARGE_NO";
            sMapingHeaderTxt = "客户         ,费目     ,收支        ,交现金        ,单位     ,单价 ,数量,合计  ,收据编号  ,货代公司  ,进出口    ,结算方式  ,作业方式  ,业务单号  ,合作方       ,办单人     ,箱号      ,货物名称,计费编号";
            ggcBilling.ColumnsMappingCreate(sMapingCols.Replace(" ", ""), sMapingHeaderTxt.Replace(" ", ""));
            this.winUtil.LoadGridLayout(ggcBilling);

            //费用明细列表按收支分组
            //gridView2.GroupCount = 1;
            //gridView2.SortInfo.AddRange(new DevExpress.XtraGrid.Columns.GridColumnSortInfo[] {
            //new DevExpress.XtraGrid.Columns.GridColumnSortInfo(gridView2.Columns["IO_FLAG_DESC"], DevExpress.Data.ColumnSortOrder.Ascending)});

            //图片列表
            ggcImageList.GridView = this.gvImage;
            ggcImageList.GridView.OptionsBehavior.EditorShowMode = DevExpress.Utils.EditorShowMode.Click;
            //sGridHead = "[FILE_NAME;文件名],[BNS_IMG_SAVE;图片]";
            //ggcImageList.ColumnsMappingCreate(sGridHead);
            gvImage.RowHeight = 100;
            this.winUtil.LoadGridLayout(ggcImageList);
            gvImage.OptionsBehavior.Editable = false;//网格不能编辑
            
            //添加tips
            ToolTipTitleItem toTipItem = new ToolTipTitleItem();
            SuperToolTip supTip = new SuperToolTip();
            toTipItem.Text = "生成(F6)";
            supTip.Items.Add(toTipItem);
            ctrAgyBns1.barCreate.SuperTip = supTip;

            isInitBillGrid = true;

            //初始化计费
            eyBillRq.sqlHelp = global.basSysPara.SqlHelp;
            eyBillRq.sqliteHelp = global.basSysPara.SqliBaseHelp;
            eyBillRq.PORT_CODE = global.basSysPara.PORT_CODE;
            eyBillRq.LST_USER = global.basSysPara.UserID;
            eyBillRq.BILL_NAME = "SfcorpBill";
            eyBillRq.CHARGE_MOD = "CASH";
            bzBill = new FactoryBill(eyBillRq);

            BindCombBox();
            ClearForm();
            FormSta = "A";
            if (!string.IsNullOrWhiteSpace(ContractNo))
            {
                txtContract_No.Text = ContractNo;
                RefreshDate();
            }
            txtCash.ForeColor = Color.Red;
            txtTtlGet.ForeColor = txtTtlTo.ForeColor = txtTtlHad.ForeColor = Color.Blue;
            //办单人
            sMapingCols = "CLIENT_NAM";
            sMapingHeaderTxt = "办单人";
            string sColumnWidth = "20";
            cboClientName.ColumnsMappingCreate(sMapingCols, sMapingHeaderTxt, sColumnWidth);


            BindDtlControlEvent();

        }

        //显示行号
        private void gridView3_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
            if (e.Info.IsRowIndicator)
            {
                if (e.RowHandle >= 0)
                {
                    e.Info.DisplayText = (e.RowHandle + 1).ToString();
                }
                else if (e.RowHandle < 0 && e.RowHandle > -1000)
                {
                    e.Info.Appearance.BackColor = System.Drawing.Color.AntiqueWhite;
                    e.Info.DisplayText = "G" + e.RowHandle.ToString();
                }
            }
        }
        private void BindCombBox()
        {
            cboPort_Id.DataSource = dataProcessor.CopyIList<etyCodeRef>(global.ilPort);
            cboI_E_Id.DataSource = dataProcessor.CopyIList<etyCodeRef>(global.ilCIE);
            cboFee_Way_Id.DataSource = dataProcessor.CopyIList<etyCodeRef>(global.ilFeeWay);
            cboCollaborate_Id.DataSource = dataProcessor.CopyIList<etyCodeRef>(global.ilCollaboRate);
            cboCustomer_Id.DataSource = dataProcessor.CopyIList<SfcorpDLL.ety.etyCustomer>(global.ilCustomer);
            cboCntr_Corp_Cod.DataSource = dataProcessor.CopyIList<etyCodeRef>(global.ilCntrCorp);
            cboClient_Id.DataSource = dataProcessor.CopyIList<SfcorpDLL.ety.etyClient>(global.ilClient);
            cboClientName.DataSource = dataProcessor.CopyIList<SfcorpDLL.ety.etyClient>(global.ilClient);
            cboWork_Way_Id.DataSource = dataProcessor.CopyIList<etyCodeRef>(global.ilWorkWay);
            cboCntr_Siz_Cod.DataSource = dataProcessor.CopyIList<etyCodeRef>(global.ilCntrSize);
            cboCntr_Typ_Cod.DataSource = dataProcessor.CopyIList<etyCodeRef>(global.ilCntrType);
            cboCntr_Ctrl_Cod.DataSource = dataProcessor.CopyIList<etyCodeRef>(global.ilCntrCtrl);
            cboCntr_Oper_Cod.DataSource = dataProcessor.CopyIList<etyCodeRef>(global.ilCntrOper);
            cboCargoCod.DataSource = dataProcessor.CopyIList<etyCodeRef>(global.ilCargo);
            cboSpcMod.DataSource = dataProcessor.CopyIList<etyCodeRef>(global.ilBnsSpcMod);
            IList<etyCodeRef> ilForeignVvd = dataProcessor.CopyIList<etyCodeRef>(global.ilForeignVvd);
            ilForeignVvd.Insert(0, new TT.ORM.etyCodeRef() { CODE = "***", CODE_DESC = "***" });
            cboForeignVvd.DataSource = ilForeignVvd;
        }
        private void tbarRefresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                splashScreenManager1.ShowWaitForm();
            }
            catch { }
            string sContractNo = string.Empty;
            if (string.IsNullOrEmpty(txtContract_No.Text) == false)
                sContractNo = txtContract_No.Text;
            TT.Module.RefreshTable.BaseTableRefreshByTables(string.Empty, false);
            BindCombBox();
            ClearForm();
            ClearForm();
            txtContract_No.Text = sContractNo;
            RefreshDate();
            try{ splashScreenManager1.CloseWaitForm();  } catch { }
        }

        private void tbarNew_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                splashScreenManager1.ShowWaitForm();
            }
            catch { }
            NewData();
            try{ splashScreenManager1.CloseWaitForm();  } catch { }
        }

        private void tbarSave_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                splashScreenManager1.ShowWaitForm();
            }
            catch { }
            SaveDate();
            try{ splashScreenManager1.CloseWaitForm();  } catch { }
        }

        private void tbarDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                splashScreenManager1.ShowWaitForm();
            }
            catch { }
            DeleteDate();
            try{ splashScreenManager1.CloseWaitForm();  } catch { }
        }

        public override etyQuickKey F7()
        {
            etyFrtAgyBns eyBns = new etyFrtAgyBns();
            IList<QueryItem> ilQueryItem = new List<QueryItem>();
            ilQueryItem = this.GetQueryItemFromLabel(this, ref ilQueryItem);

            etyUserProfile ey = new etyUserProfile();
            ey.DATA_SOURCE = "dsOrder";
            ey.DESCRIPTION = "1111";
            ey.IDENTITY = "root";
            ey.INFO = "NAME(*^)11(&^)order_date(*^)22(&^)customer_no(*^)33(&^)";
            ey.PRES_OBJECT = "App.Order.frmCustomerOrder";
            ey.TYPE_FLAG = "Q";

            //frmQuery fmQuery = new frmQuery(ey, eyBns, ilQueryItem);
            //fmQuery.ShowDialog();
            return base.F7();
        }

        private void tbarSearch_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            F7();
        }

        private void tbarExit_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            F12();
        }

        public override Dev.Control.etyQuickKey RefreshDate()
        {
            GetAgyBns();
            return base.RefreshDate();
        }

        private void GetAgyBns()
        {
            if (string.IsNullOrWhiteSpace(txtContract_No.Text))
            {
                return;
            }

            etyFrtAgyBns ey = new etyFrtAgyBns();
            ey.CONTRACT_NO = txtContract_No.Text.Trim();
            ilAnyBnsDtl = bzAgyBns.GetFrtAgyBns(ey);            //**取得数据
            if (ilAnyBnsDtl.Count <= 0)
            {
                TT.HelpInfo.MsgBox.ShowSuccessBox("该业务单号不存在");
                return;
            }

            if (ilAnyBnsDtl[0].BNS_STATUS_D == "D")
                bnsStatus = "D";
            else
                bnsStatus = ilAnyBnsDtl[0].BNS_STATUS_D;
            

            eyBnsHdr = ilAnyBnsDtl[0];
            TT.Common.formProcess.SetFormEntity(ilAnyBnsDtl[0], grpBns);

            srcBinding.DataSource = ilAnyBnsDtl;
            ggcDtl.DataSource = srcBinding;
            ggcDtl.AutoColumnWidth();
            ggcDtl.GridView.ClearSelection();
            ggcDtl.Columns["CNTR"].Width = 200;
            GetCboText();
            FormSta = "E";

            Billing(false);

            GetBnsImgs(ey);

            SumCountContainer();
        }
        private void GetBnsImgs(etyFrtAgyBns ey)
        {
            ilImageList = bzAgyBns.BnsImageTableGet(ey);
            ilAddImgList.Clear();
            ilDelImgList.Clear();
            foreach (etyFrtAgyBns img in ilImageList)
            {
                //20150505选择图片后，System.IO.Directory.GetCurrentDirectory()会变成选择图片的路径，汗
                //img.BNS_IMG_SAVE = TT.Common.ImageProcess.getImageByte(System.IO.Directory.GetCurrentDirectory() + @"\image\bnsReport.gif");
                img.BNS_IMG_SAVE = TT.Common.ImageProcess.getImageByte(global.ProgramPath + @"\image\bnsReport.gif");
            }
            srcImage.DataSource = ilImageList;
            ggcImageList.DataSource = srcImage;
            ggcImageList.AutoColumnWidth();
        }
        private void GetCboText()
        {
            cboPort_Id.GetCodeText();
            cboI_E_Id.GetCodeText();
            cboFee_Way_Id.GetCodeText();
            cboCustomer_Id.GetCodeText();
            cboCntr_Corp_Cod.GetCodeText();
            cboClient_Id.GetCodeText();
            cboCollaborate_Id.GetCodeText();
            cboWork_Way_Id.GetCodeText();
            cboCntr_Siz_Cod.GetCodeText();
            //cboCntr_Typ_Cod.GetCodeText();
            //cboCargo_Cod.GetCodeText();
            cboBooking_Paper_Type.GetCodeText();
            cboCntr_Ctrl_Cod.GetCodeText();
            cboCntr_Oper_Cod.GetCodeText();
            cboSpcMod.GetCodeText();
            cboForeignVvd.GetCodeText();
        }
        //新建
        public override etyQuickKey NewData()
        {
            txtContract_No.Focus();
            FormSta = "A";
            bnsStatus = "N";
            ClearForm();
            ClearForm();//下拉控件有点BUG，当选择第2行之后的记录时，要调用两次才能清掉选项
            return base.NewData();
        }
        //删除
        public override etyQuickKey DeleteDate()
        {
            if (string.IsNullOrWhiteSpace(txtContract_No.Text))
                return null;

            etyFrtAgyBns eyFabCon = srcBinding.Current as etyFrtAgyBns;

            //IList<etyFrtAgyBnsCon> ilFabCon = srcBinding.DataSource as IList<etyFrtAgyBnsCon>;
            bool success;
            //if (eyFabCon == null)//如果没有选中记录点删除的话，删除整个业务单信息。
            //{
            if (TT.HelpInfo.MsgBox.ShowQuestionBox(string.Format("是否删除整个业务单：{0}？", new string[] { txtContract_No.Text })))
            {
                success = bzAgyBns.Delete_AgyBnsDoc(new etyFrtAgyBns() { CONTRACT_NO = txtContract_No.Text, CANCEL_NAM = global.basSysPara.UserID });
                if (success)
                {
                    TT.HelpInfo.MsgBox.ShowSuccessBox("删除成功");
                    NewData();
                }
                else
                    TT.HelpInfo.MsgBox.ShowSuccessBox("删除失败");
            }
            else
                return base.DeleteDate();
            //}
            //else
            //{
            //    if (TT.HelpInfo.MsgBox.ShowQuestionBox("是否删除选中的业务单明细记录？"))
            //    {
            //        success = biz.Delete_AgyBnsCon(eyFabCon);
            //        if (success)
            //        {
            //            TT.HelpInfo.MsgBox.ShowSuccessBox("删除成功");
            //            RefreshDate();
            //        }
            //        else
            //            TT.HelpInfo.MsgBox.ShowSuccessBox("删除失败");
            //    }
            //    else
            //        return base.DeleteDate();
            //}

            return base.DeleteDate();
        }
        //保存
        public override etyQuickKey SaveDate()
        {
            txtContract_No.Focus();//避免在网格中修改完箱号，焦点还没离开网格时获取不到网格最新的值
            etyFrtAgyBns eyDoc = new etyFrtAgyBns();
            TT.Common.formProcess.GetFormEntity(eyDoc, grpBns);

            if (!check_hdr(eyDoc))
            {
                return base.SaveDate();
            }
            IList<etyFrtAgyBns> ilCon = srcBinding.DataSource as List<etyFrtAgyBns>;
            if (FormSta == "A")
            {
                //判断提单号是否在系统中已经存在
                string blNos = "";
                foreach (etyFrtAgyBns con in ilCon)
                {
                    if (!string.IsNullOrWhiteSpace(con.SEA_BILL_NO))
                        blNos += con.SEA_BILL_NO + ",";
                }
                blNos = blNos.TrimEnd(',');
                IList<etyFrtAgyBns> blBnsList = bzAgyBns.GetFrtAgyBns(new etyFrtAgyBns() { SEA_BILL_NO = blNos });
                if (blBnsList.Count > 0)
                {
                    frmAgyBnsTD fmBnsBlNo = new frmAgyBnsTD(blBnsList);
                    if (fmBnsBlNo.ShowDialog() == DialogResult.No)
                        return base.SaveDate();
                }
                if (bzAgyBns.Insert_AgyBns(eyDoc, ilCon))    //** 插入
                {
                    //Billing(true);
                    foreach (etyFrtAgyBns eyImage in ilImageList)
                    {
                        eyImage.CONTRACT_NO = eyDoc.CONTRACT_NO;
                        if (!bzAgyBns.BnsImageInsert(eyImage))        //保存图片
                        {
                            TT.HelpInfo.MsgBox.ShowWarnBox("图片：" + eyImage.FILE_NAME + "保存失败");
                        }
                    }
                    //TT.HelpInfo.MsgBox.ShowSuccessBox("业务单保存成功");
                    txtContract_No.Text = eyDoc.CONTRACT_NO;
                    RefreshDate();

                    //保存成功，自动计费
                    Billing(true);
                    xtraTabControl1.SelectedTabPageIndex = 1;

                    bnsStatus = "N";        //插入保存后锁单状态为N，重新读入时才锁。
                }
                else
                {
                    TT.HelpInfo.MsgBox.ShowWarnBox("保存失败");
                }
            }
            else if (FormSta == "E")
            {
                if (string.IsNullOrWhiteSpace(eyDoc.CONTRACT_NO) || eyDoc.CONTRACT_NO != curContractNo)
                {
                    TT.HelpInfo.MsgBox.ShowSuccessBox("请先刷新出业务单信息再进行编辑保存");
                    txtContract_No.Focus();
                    try{ splashScreenManager1.CloseWaitForm();  } catch { }
                    return base.SaveDate();
                }
                eyDoc.UPDATE_NAM = global.basSysPara.UserID;
                if (bzAgyBns.Update_AgyBns(eyDoc, ilCon, delFabConList))
                {
                    //TT.HelpInfo.MsgBox.ShowSuccessBox("更新业务单成功");
                    RefreshDate();
                    Billing(true);
                }
                else
                {
                    TT.HelpInfo.MsgBox.ShowWarnBox("更新业务单失败");
                }
            }
            //显示计费
            //if(ilChrg.Count<=0)
            //    F8();

            return base.SaveDate();
        }

        private void ClearForm()
        {
            //清抬头
            txtContract_No.Text = "";
            cboPort_Id.SelectedIndex = -1;
            cboI_E_Id.SelectedIndex = -1;
            cboFee_Way_Id.SelectedIndex = -1;
            txtRec_Nam.Text = global.basSysPara.UserID;
            dateRec_Tim.DateTime = DateTime.Now;
            txtUpdate_Nam.Text = "";
            dateUpdate_Tim.DateTime = DateTime.Now;
            cboCustomer_Id.SelectedIndex = -1;
            txtClient_Contact.Text = "";
            cboClientName.Text = "";

            //清网格
            IList<etyFrtAgyBnsCon> dtlList = new List<etyFrtAgyBnsCon>();
            srcBinding.DataSource = dtlList;
            ggcDtl.DataSource = srcBinding;
            ggcDtl.AutoColumnWidth();

            //清明细
            txtSea_Bill_No.Text = "";
            txtAgent_Bill_No.Text = "";
            txtBooking_No.Text = "";
            cboWork_Way_Id.SelectedIndex = -1;
            cboCntr_Siz_Cod.SelectedIndex = -1;
            cboCntr_Typ_Cod.SelectedIndex = -1;
            txtCntrCount.Text = "";
            txtShip_Nam.Text = "";
            txtVoyage.Text = "";
            //cboCargo_Cod.SelectedIndex = -1;
            txtUndg_No.Text = "";
            txtFlow_Cod.Text = "";
            cboCntr_Ctrl_Cod.SelectedIndex = -1;
            cboCntr_Oper_Cod.SelectedIndex = -1;
            chkWgtFlag.Checked = false;
            cboSpcMod.SelectedIndex = 0;
            cboCollaborate_Id.SelectedIndex = 0;
            //cboForeignVvd.SelectedIndex = 2;
            cboForeignVvd.Text = "1";
            delFabConList = new List<etyFrtAgyBns>();

            barCntrCount.Caption = string.Empty;

            //下拉默认出口
            IList<etyCodeRef> ilIe = cboI_E_Id.DataSource as IList<etyCodeRef>;
            foreach (etyCodeRef ie in ilIe)
            {
                if (ie.CODE == "E")
                {
                    cboI_E_Id.SelectedItem = ie;
                    cboI_E_Id.GetCodeText();
                }
            }
            //下拉默认陆运重进
            IList<etyCodeRef> ilWorkWay = cboWork_Way_Id.DataSource as IList<etyCodeRef>;
            foreach (etyCodeRef iWorkWay in ilWorkWay)
            {
                if (iWorkWay.CODE == "FINO")
                {
                    cboWork_Way_Id.SelectedItem = iWorkWay;
                    cboWork_Way_Id.GetCodeText();
                }
            }
            //内外贸
            cboForeignVvd.GetCodeText();
            cboCollaborate_Id.GetCodeText();
            xtraTabControl1.SelectedTabPageIndex = 0;

            ilImageList.Clear();
            ilAddImgList.Clear();
            ilDelImgList.Clear();
            srcImage.DataSource = ilImageList;
            ggcImageList.DataSource = srcImage;
            ggcImageList.AutoColumnWidth();

            cboFee_Way_Id.SelectedIndex = -1;
            cboClient_Id.SelectedIndex = -1;
            cboClient_Id.Text = "";
            cboCntr_Corp_Cod.SelectedIndex = -1;
        }
        private bool check_hdr(etyFrtAgyBns ey)
        {
            if (string.IsNullOrEmpty(ey.PORT_ID.Trim()))
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("码头不能为空");
                cboPort_Id.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(ey.I_E_ID.Trim()))
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("进出口标志不能为空");
                cboI_E_Id.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(ey.FEE_WAY_ID.Trim()))
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("结算方式不能为空");
                cboFee_Way_Id.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(ey.COLLABORATE_ID.Trim()))
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("合作方不能为空");
                cboCollaborate_Id.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(ey.CUSTOMER_ID.Trim()))
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("客户不能为空");
                cboCustomer_Id.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(ey.CNTR_CORP_COD.Trim()))
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("合作方不能为空");
                cboCntr_Corp_Cod.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(ey.CLIENT_ID.Trim()))
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("办单人不能为空");
                cboClient_Id.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(cboForeignVvd.Text.Trim()))
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("内外贸标识不能为空");
                cboForeignVvd.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(cboSpcMod.Text.Trim()))
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("特别处理不能为空");
                cboSpcMod.Focus();
                return false;
            }
            return true;
        }
        private bool check_dtl(etyFrtAgyBns ey)
        {
            //if (string.IsNullOrEmpty(ey.BOOKING_NO.Trim()))
            //{
            //    TT.HelpInfo.MsgBox.ShowWarnBox("SO送单号不能为空");
            //    txtBooking_No.Focus();
            //    return false;
            //}
            if (string.IsNullOrEmpty(ey.CNTR_SIZ_COD.Trim()))
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("箱尺寸不能为空");
                cboCntr_Siz_Cod.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(ey.CNTR_TYP_COD.Trim()))
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("箱类型不能为空");
                cboCntr_Typ_Cod.Focus();
                return false;
            }
            if (string.IsNullOrEmpty(txtCntrCount.Text.Trim()))
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("箱数不能为空");
                txtCntrCount.Focus();
                return false;
            }
            int iCntrCount;
            if (!int.TryParse(txtCntrCount.Text.Trim(), out iCntrCount) || iCntrCount < 1)
            {
                TT.HelpInfo.MsgBox.ShowWarnBox("箱数必须大于0");
                txtCntrCount.Focus();
                return false;
            }
            return true;
        }

        private void btnBuild_Click(object sender, EventArgs e)
        {
            //etyFrtAgyBns ey = new etyFrtAgyBns();
            //TT.Common.formProcess.GetFormEntity(ey, panelControl1);
            //if (!string.IsNullOrWhiteSpace(ey.WORK_WAY_ID))
            //    ey.WORK_WAY_NAM = global.ilWorkWay.First<etyCodeRef>(ety => { return ety.CODE == ey.WORK_WAY_ID; }).CODE_DESC;
            //if(!string.IsNullOrWhiteSpace(ey.CARGO_COD))
            //    ey.CARGO_NAM = global.ilCargo.First<etyCodeRef>(ety => { return ety.CODE == ey.CARGO_COD; }).CODE_DESC;
            //if (!string.IsNullOrWhiteSpace(ey.FOREIGN_VVD))
            //    ey.FOREIGN_VVD_DESC = global.ilForeignVvd.First<etyCodeRef>(ety => { return ety.CODE == ey.FOREIGN_VVD; }).CODE_DESC;
            //if (!string.IsNullOrWhiteSpace(ey.BNS_SPC_MOD))
            //    ey.BNS_SPC_MOD_DESC = global.ilBnsSpcMod.First<etyCodeRef>(ety => { return ety.CODE == ey.BNS_SPC_MOD; }).CODE_DESC;


            ////TT.Common.formProcess.GetFormEntity(ey, panelControl2);
            //if (!check_dtl(ey))
            //    return;
            //IList<etyFrtAgyBns> dtlList;
            //dtlList = srcBinding.DataSource as IList<etyFrtAgyBns>;
            //if (dtlList == null || dtlList.Count < 1)
            //    dtlList = new List<etyFrtAgyBns>();
            //for (int i = 0; i < int.Parse(txtCntrCount.Text.Trim()); i++)
            //{
            //    //dtlList.Add((etyFrtAgyBns)ey.Clone()); 
            //    dtlList.Add(dataProcessor.CopyIList<etyFrtAgyBns>(new List<etyFrtAgyBns>() { ey })[0]);
            //}
            //srcBinding.DataSource = dtlList;
            //ggcDtl.DataSource = srcBinding;
            //ggcDtl.AutoColumnWidth();
        }

        private void cboClient_Id_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (String.IsNullOrEmpty(cboClient_Id.Text)) return;
            txtClient_Contact.Text = cboClient_Id.GetValue("CLIENT_CONTACT");
            //cboClientName.Text = cboClient_Id.Text;
        }

        private void txtContract_No_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                RefreshDate();
            }
        }

        private void ggcDtl_Click(object sender, EventArgs e)
        {
            etyFrtAgyBns ey = srcBinding.Current as etyFrtAgyBns;
            if (ey == null)
                return;
            TT.Common.formProcess.SetFormEntity(ey, panelControl1);
            GetCboText();
            //BindDtlControlEvent();
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {

        }
        IList<etyFrtAgyBns> delFabConList = new List<etyFrtAgyBns>();
        private void btnRemove_Click(object sender, EventArgs e)
        {

        }

        bool isInitBillGrid = false;
        private void xtraTabControl1_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            if (xtraTabControl1.TabIndex == 1 && !isInitBillGrid)
            {

            }

        }

        #region 计费相关

        //计算
        private void tbarCacula_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            F8();
        }
        //保存
        private void tbarSaveBill_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            F9();
        }

        //计费
        public override etyQuickKey F8()
        {
            try
            {
                splashScreenManager1.ShowWaitForm();
            }
            catch { }
            Billing(true);
            xtraTabControl1.SelectedTabPageIndex = 1;
            try { splashScreenManager1.CloseWaitForm(); }
            catch { }
            return base.F8();
        }

        //保存计费
        private void SaveBilling()
        {
            if (ilChrg.Count <= 0)
            {
                TT.HelpInfo.MsgBox.ShowSuccessBox("业务单保存成功。");
                return;
            }
            try { splashScreenManager1.ShowWaitForm(); }
            catch { }
            foreach (etyChargeDtl ey in ilChrg)
            {
                if (string.IsNullOrEmpty(ey.AMOUNT) || string.IsNullOrEmpty(ey.PRICE_SEQ))
                {
                    TT.HelpInfo.MsgBox.ShowWarnBox("需收之费用未定义价格，请定义价格后重新计算费用再保存。");
                    try { splashScreenManager1.CloseWaitForm(); }
                    catch { }
                    return ;
                }
            }
            bool isSave = bzBill.SaveChargeHdrDtl(ilChrg);
            try { splashScreenManager1.CloseWaitForm(); }
            catch { }
            if (isSave)
            {
                tbarSaveBill.Enabled = false;
                Billing(false);

                if (Convert.ToDouble(txtCash.EditValue) > 0)
                    TT.HelpInfo.MsgBox.ShowSuccessBox(
                        string.Format( "保存成功！\n\r请交费 {0}元 ",new string[]{txtCash.Text})
                        );
                else
                    TT.HelpInfo.MsgBox.ShowSuccessBox("业务单保存成功。");
                
                //JustMe 20150623 计完不再显示，点编辑显示
                //ShowGetMoney(false);
            }
            else
            {
                TT.HelpInfo.MsgBox.ShowSuccessBox("计费失败！请联系系统管理员。");
            }
        }

        private void ShowGetMoney(bool mstShow)
        {
            //mstShow  是否强行显示
            if (Convert.ToDouble(txtCash.EditValue) > 0 || mstShow)
            {
                eyBillRq.BILL_KEY1 = eyBnsHdr.FABC_GKEY;
                eyBillRq.BILL_KEY2 = eyBnsHdr.CONTRACT_NO;
                eyBillRq.CUSTOMER = eyBnsHdr.CUSTOMER_ID;

                frmAgyBnsBillMain fmBill = new frmAgyBnsBillMain(ilChrg, eyBillRq, type_view_bill.bnsCash, null, bzBill);
                fmBill.ShowDialog();
                Billing(false);
            }
        }

        private void Billing(bool isNeetBill)
        {
            etyChargeDtl eyChrg = new etyChargeDtl();
            eyChrg.CHRG_FLT20 = txtContract_No.Text.Trim();
            ilChrg = bzAgyBns.GetBillResult(eyChrg);
            if (ilChrg.Count <= 0)
            {
                if (isNeetBill)     //要计费的，点计费按钮，调用业务单就不用了。
                {
                    //刷新界面所需要的数据
                    string rst = TT.Module.RefreshTable.BaseTableRefreshByTables("BILL_CODE,CODE_REF,VW_BILL_PRICE,VW_BILL_PROJECT", false);
                    if (rst != "1")
                    {
                        TT.HelpInfo.MsgBox.ShowWarnBox("业务单保存成功。\n\r计费费用出错，请联系管理员。");
                        return;
                    }
                    //初始化计费
                    eyBillRq.BILL_KEY1 = txtContract_No.Text.Trim();
                    eyBllPara = bzBill.Billing(eyBillRq);

                    ilChrg = bzBill.GetBilledDtl(eyBillRq);

                    SaveBilling();   //保存计费
                    isNeetBill = false;
                }
            }
            else
            {
                isBilled = true;
                tbarSaveBill.Enabled = false;
            }

            IList<etyChargeDtl> ilChrg_I = new List<etyChargeDtl>();
            IList<etyChargeDtl> ilChrg_O = new List<etyChargeDtl>();
            //应收
            foreach (etyChargeDtl ey in ilChrg)
            {
                if (ey.IO_FLAG == "1")
                    ilChrg_I.Add(ey);
                else
                    ilChrg_O.Add(ey);
            }
            //应收
            srcBill.DataSource = new List<etyChargeDtl>();
            srcBill.DataSource = ilChrg;
            ggcBilling.DataSource = srcBill;
            ggcBilling.AutoColumnWidth();
            ggcBilling.GridView.ClearSelection();

            BillCacula();

            if (isNeetBill)
            {
                //JustMe 20150623 计完不再显示，点编辑显示
                //ShowGetMoney(false);
            }
        }

        private void BillCacula()
        {
            double dbGet = 0; double dbTo = 0; double dbCash = 0;
            foreach (etyChargeDtl ey in ilChrg)
            {
                //收
                if (ey.IO_FLAG == "1")
                {
                    dbGet += ey.AMOUNT_DB;
                    if (ey.CASH_FLAG == "1")        //现金
                    {
                        dbCash += ey.AMOUNT_DB;
                    }
                }
                else//支
                {
                    if (ey.AMOUNT_DB < 0)             //茶水费情况
                    {
                        dbCash += ey.AMOUNT_DB;    //要少收现金
                        dbGet += ey.AMOUNT_DB;
                    }
                    else
                        dbTo += ey.AMOUNT_DB;
                }

            }
            txtTtlGet.Text = dbGet.ToString().Trim();
            txtTtlTo.Text = dbTo.ToString().Trim();
            txtTtlHad.Text = (dbGet - dbTo).ToString().Trim();
            txtCash.Text = dbCash.ToString().Trim();
        }

        #endregion

        //打印(非箱)
        public override etyQuickKey F11()
        {
            PrintAccount("MtyCntr");
            return base.F11();
        }

        private void tbarPrint_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            PrintAccount(e.Item.Tag.ToString());
        }

        public void PrintAccount(string iPrtType)
        {
            splashScreenManager1.ShowWaitForm();
            bizRptMainForm bzRptMain;
            bzRptMain = new bizRptMainForm(global.basSysPara.SqlHelp, global.basSysPara.PORT_CODE);
            DataSet dsRptParam = new DataSet();
            etyRptDtl eyRpt = new etyRptDtl();
            if (iPrtType == "MtyCntr")
                eyRpt.RPT_NAME = "收款收据(非箱)";
            else
                eyRpt.RPT_NAME = "收款收据(显箱)";
            eyRpt = bzRptMain.GetRptDtl(eyRpt)[0];

            dsRptParam = TT.Common.xmlProcessor.GetXmlDataSetFromString(eyRpt.RPT_DTL);

            if (dsRptParam == null) return;

            Hashtable htParam = new Hashtable();
            htParam.Add("CONTRACT_NO", txtContract_No.Text.Trim());
            htParam.Add("USER_ID", global.basSysPara.UserID);
            string sRtn = bzRptMain.PrintXLS(dsRptParam, htParam);
            try { splashScreenManager1.CloseWaitForm(); }
            catch { }
            if (sRtn != "1")
                TT.HelpInfo.MsgBox.ShowWarnBox(sRtn);
        }

        public override etyQuickKey F6()
        {
            etyFrtAgyBns ey = new etyFrtAgyBns();
            TT.Common.formProcess.GetFormEntity(ey, grpBns);
            if (!check_hdr(ey))
            {
                return null;
            }
            TT.Common.formProcess.GetFormEntity(ey, panelControl1);

            if (!check_dtl(ey))
                return null;

            IList<etyFrtAgyBns> dtlList;
            dtlList = srcBinding.DataSource as IList<etyFrtAgyBns>;
            if (dtlList == null || dtlList.Count < 1)
                dtlList = new List<etyFrtAgyBns>();
            for (int i = 0; i < int.Parse(txtCntrCount.Text.Trim()); i++)
            {
                ey = new etyFrtAgyBns();
                TT.Common.formProcess.GetFormEntity(ey, grpBns);
                TT.Common.formProcess.GetFormEntity(ey, panelControl1);

                if (!string.IsNullOrWhiteSpace(ey.WORK_WAY_ID))
                    ey.WORK_WAY_NAM = global.ilWorkWay.First<etyCodeRef>(ety => { return ety.CODE == ey.WORK_WAY_ID; }).CODE_DESC;
                if (!string.IsNullOrWhiteSpace(ey.CARGO_COD))
                    ey.CARGO_NAM = global.ilCargo.First<etyCodeRef>(ety => { return ety.CODE == ey.CARGO_COD; }).CODE_DESC;
                if (!string.IsNullOrWhiteSpace(ey.FOREIGN_VVD) && ey.FOREIGN_VVD != "***")
                    ey.FOREIGN_VVD_DESC = global.ilForeignVvd.First<etyCodeRef>(ety => { return ety.CODE == ey.FOREIGN_VVD; }).CODE_DESC;
                if (!string.IsNullOrWhiteSpace(ey.BNS_SPC_MOD) && ey.BNS_SPC_MOD != "***")
                    ey.BNS_SPC_MOD_DESC = global.ilBnsSpcMod.First<etyCodeRef>(ety => { return ety.CODE == ey.BNS_SPC_MOD; }).CODE_DESC;

                dtlList.Add(ey);
            }
            srcBinding.DataSource = dtlList;
            ggcDtl.DataSource = srcBinding;
            ggcDtl.AutoColumnWidth();

            SumCountContainer();
            return base.F6();
        }

        private void SumCountContainer()
        {
            string s = "       {0}'     {1}个";
            IList<etyFrtAgyBns> ilCon = srcBinding.DataSource as List<etyFrtAgyBns>;
            int i20 = 0;
            int i40 = 0;
            int i45 = 0;
            string s20 = string.Empty;
            string s40 = string.Empty;
            string s45 = string.Empty;
            foreach (etyFrtAgyBns ey in ilCon)
            {
                switch (ey.CNTR_SIZ_COD)
                {
                    case "20":
                        i20++;
                        s20 = string.Format(s, new string[] { ey.CNTR_SIZ_COD, i20.ToString() });
                        break;
                    case "40":
                        i40++;
                        s40 = string.Format(s, new string[] { ey.CNTR_SIZ_COD, i40.ToString() });
                        break;
                    case "45":
                        i45++;
                        s45 = string.Format(s, new string[] { ey.CNTR_SIZ_COD, i45.ToString() });
                        break;
                }
            }
            barCntrCount.Caption = s20 + s40 + s45;
        }

        private void cboCustomer_Id_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(cboCustomer_Id.Value))
            {
                IList<etyCodeRef> ilFeeWayId = cboFee_Way_Id.DataSource as IList<etyCodeRef>;
                foreach (etyCodeRef feeWayId in ilFeeWayId)
                {
                    if (feeWayId.CODE == cboCustomer_Id.GetValue("FEE_WAY_ID"))
                    {
                        cboFee_Way_Id.SelectedItem = feeWayId;
                        cboFee_Way_Id.GetCodeText();
                        return;
                    }
                }
            }
        }

        public object eyBill { get; set; }

        private void ggcDtl_DoubleClick(object sender, EventArgs e)
        {
            //if (ggcDtl.CurrentColName == "BNS_IMG" && ggcDtl.CurrentRowIndex >= 0)
            //{
            //    etyFrtAgyBns ey = srcBinding.Current as etyFrtAgyBns;
            //    if (ey == null)
            //        return;
            //    if (!string.IsNullOrEmpty(ey.BNS_IMG_LEN))
            //    {
            //        System.Windows.Forms.DialogResult rst =
            //            MessageBox.Show("显示图片请选择【是】\r\n重新上传请选择【否】\r\n退出按取消"
            //            , "请选择", MessageBoxButtons.YesNoCancel);
            //        if (rst == System.Windows.Forms.DialogResult.Yes)
            //        {
            //            //显示图片
            //            //etyFrtAgyBns eyImage = new etyFrtAgyBns();
            //            //eyImage = bzAgyBns.GetFrtAgyBnsImage(ey);
            //            //frmViewBnsImage frm = new frmViewBnsImage(eyImage.BNS_IMG_SAVE);
            //            //frm.ShowDialog();
            //            //return;
            //        }
            //        if (rst == System.Windows.Forms.DialogResult.Cancel)
            //            return;
            //    }

            //    OpenFileDialog fileDialog = new OpenFileDialog();
            //    fileDialog.Multiselect = true;
            //    fileDialog.Title = "请选择文件";
            //    fileDialog.Filter = "(*.jpg,*.png,*.jpeg,*.bmp,*.gif)|*.jgp;*.png;*.jpeg;*.bmp;*.gif|All files(*.*)|*.*";

            //    if (fileDialog.ShowDialog() == DialogResult.OK)
            //    {
            //        etyFrtAgyBns eyImg = new etyFrtAgyBns();
            //        eyImg.BNS_IMG_LEN = "-1";
            //        //表格赋值
            //        gridView1.SetRowCellValue(ggcDtl.CurrentRowIndex, gridView1.Columns["BNS_IMG_LEN"], eyImg.BNS_IMG_LEN);
            //        gridView1.SetRowCellValue(ggcDtl.CurrentRowIndex, gridView1.Columns["BNS_IMG"], eyImg.BNS_IMG);

            //        string file = fileDialog.FileName;
            //        byte[] img = TT.Common.ImageProcess.getImageByte(file);
            //        gridView1.SetRowCellValue(ggcDtl.CurrentRowIndex, gridView1.Columns["BNS_IMG_SAVE"], img);
            //        //实体赋值
            //        ey.BNS_IMG_LEN = "-1";
            //        ey.BNS_IMG_SAVE = img;
            //    }

            //}
        }

        #region 控件自动绑定事件
        private void BindDtlControlEvent()
        {
            foreach (System.Windows.Forms.Control ctrl in panelControl1.Controls)
            {
                if (ctrl is Dev.Control.cTextEdit)
                {
                    Dev.Control.cTextEdit txtBox = ctrl as Dev.Control.cTextEdit;
                    txtBox.TextChanged -= new EventHandler(DetailTextBoxChanged);
                    txtBox.TextChanged += new EventHandler(DetailTextBoxChanged);
                }
                else if (ctrl is Dev.Control.MultiColumnComboBox)
                {
                    Dev.Control.MultiColumnComboBox cboBox = ctrl as Dev.Control.MultiColumnComboBox;
                    cboBox.SelectedIndexChanged -= new EventHandler(DetailCboSelIndexChanged);
                    cboBox.SelectedIndexChanged += new EventHandler(DetailCboSelIndexChanged);
                }
                else if (ctrl is Dev.Control.Control.cComboBoxEdit)
                {
                    Dev.Control.Control.cComboBoxEdit cboBox = ctrl as Dev.Control.Control.cComboBoxEdit;
                    cboBox.SelectedIndexChanged -= new EventHandler(DetailCboSelIndexChanged);
                    cboBox.SelectedIndexChanged += new EventHandler(DetailCboSelIndexChanged);
                    cboBox.TextChanged += new EventHandler(DetailCboSelIndexChanged);
                }
                else if (ctrl is Dev.Control.cCheckBox)
                {
                    Dev.Control.cCheckBox chkBox = ctrl as Dev.Control.cCheckBox;
                    chkBox.CheckedChanged -= new EventHandler(DetailChkBoxChanged);
                    chkBox.CheckedChanged += new EventHandler(DetailChkBoxChanged);
                }
            }
        }
        private void RemoveDtlControlEvent()
        {
            foreach (System.Windows.Forms.Control ctrl in panelControl1.Controls)
            {
                if (ctrl is Dev.Control.cTextEdit)
                {
                    Dev.Control.cTextEdit txtBox = ctrl as Dev.Control.cTextEdit;
                    txtBox.TextChanged -= new EventHandler(DetailTextBoxChanged);
                }
                else if (ctrl is Dev.Control.MultiColumnComboBox)
                {
                    Dev.Control.MultiColumnComboBox cboBox = ctrl as Dev.Control.MultiColumnComboBox;
                    cboBox.SelectedIndexChanged -= new EventHandler(DetailCboSelIndexChanged);
                }
                else if (ctrl is Dev.Control.MultiColumnComboBox)
                {
                    Dev.Control.MultiColumnComboBox cboBox = ctrl as Dev.Control.MultiColumnComboBox;
                    cboBox.SelectedIndexChanged += new EventHandler(DetailCboSelIndexChanged);
                }
                else if (ctrl is Dev.Control.cCheckBox)
                {
                    Dev.Control.cCheckBox chkBox = ctrl as Dev.Control.cCheckBox;
                    chkBox.CheckedChanged -= new EventHandler(DetailChkBoxChanged);
                }
            }
        } 
        private void DetailTextBoxChanged(object sender, EventArgs e)
        {
            EditDetailGrid();
        }

        private void DetailCboSelIndexChanged(object sender, EventArgs e)
        {
            EditDetailGrid();
        }

        private void DetailChkBoxChanged(object sender, EventArgs e)
        {
            EditDetailGrid();
        }
        private void EditDetailGrid()
        {
            if (ggcDtl.Focused) return;     //JustMe20150604
            //JustMe20150605 不再使用这种方式更改数据
            //etyFrtAgyBns ey = srcBinding.Current as etyFrtAgyBns;
            //if (ey == null)
            //{
            //    return;
            //}
            //TT.Common.formProcess.GetFormEntity(ey, panelControl1);
            //srcBinding.ResetCurrentItem();
        }
        #endregion

        //编辑下拉换值
        private void gvBns_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {

            switch (e.Column.Name)
            {
                case "CNTR":
                    string cntr = e.Value.ToString();
                    if (!string.IsNullOrWhiteSpace(cntr))
                    {
                        if (!TT.Common.ContainerProcess.ContainerNumberCheck(cntr))
                        {
                            TT.HelpInfo.MsgBox.ShowWarnBox("柜号:" + cntr + "校验失败，请重新输入");
                        }
                    }
                    break;
                case "WORK_WAY_NAM":
                    GridGetComboVal(e, "CODE", "WORK_WAY_ID");
                    break;
                case "FOREIGN_VVD_DESC":
                    GridGetComboVal(e, "CODE", "FOREIGN_VVD");
                    break;
                case "BNS_SPC_MOD_DESC":
                    GridGetComboVal(e, "CODE", "BNS_SPC_MOD");
                    break;
            }
        }

        private string GridGetComboVal(CellValueChangedEventArgs e,string Desc,string ID)
        {
            try
            {
                string colValue = string.Empty;
                DataTable dtCombo;
                if (dsComboSource.Tables.Contains(e.Column.Name))
                {
                    dtCombo = dsComboSource.Tables[e.Column.Name];
                    colValue = dtCombo.
                        Select(string.Format("{0}='{1}'", new string[] { dtCombo.DisplayExpression, e.Value.ToString() }))
                        [0][Desc].ToString();
                    gvBns.SetRowCellValue(ggcDtl.CurrentRowIndex, gvBns.Columns[ID], colValue);
                }
                if(string.IsNullOrEmpty(colValue))
                    TT.HelpInfo.MsgBox.ShowWarnBox("编辑数据出错，请联系系统管理员。");
                return colValue;
            }
            catch (Exception ex)
            {
                TT.HelpInfo.MsgBox.ShowWarnBox(ex.ToString());
                return "";
            }
        }

        private void gvBill_RowUpdated(object sender, RowObjectEventArgs e)
        {
            //etyChargeDtl etyChrgDtl = e.Row as etyChargeDtl;
            //if (etyChrgDtl != null && !ilCreateBill.Contains(etyChrgDtl) && !ilModifyBill.Contains(etyChrgDtl))
            //    ilModifyBill.Add(etyChrgDtl);
        }

        private void ggcImageList_DoubleClick(object sender, EventArgs e)
        {
            etyFrtAgyBns ey = srcImage.Current as etyFrtAgyBns;
            if (ey == null)
                return;
            try  { splashScreenManager1.ShowWaitForm(); }
            catch { }
            if (FormSta == "E")
                ey.BNS_IMG_SAVE = bzAgyBns.BnsImageContractGet(ey);
            frmViewBnsImage frmImg = new frmViewBnsImage(ey.BNS_IMG_SAVE);
            frmImg.ShowDialog();
            try { splashScreenManager1.CloseWaitForm(); }
            catch { }
        }

        private void cboForeignVvd_SelectedIndexChanged(object sender, EventArgs e)
        {
            IList<etyFrtAgyBns> ilSrc = srcBinding.DataSource as IList<etyFrtAgyBns>;
            if (ilSrc == null || ilSrc.Count < 1)
                return;
            foreach (etyFrtAgyBns ety in ilSrc)
            {
                string foreignVvd = cboForeignVvd.Value;
                ety.FOREIGN_VVD = foreignVvd;
                if (string.IsNullOrWhiteSpace(foreignVvd) || foreignVvd == "***")
                    ety.FOREIGN_VVD_DESC = "";
                else
                    ety.FOREIGN_VVD_DESC = global.ilForeignVvd.First<etyCodeRef>(ey => { return ey.CODE == ety.FOREIGN_VVD; }).CODE_DESC;
            }
            for (int i = 0; i < ilSrc.Count; i++)
                srcBinding.ResetItem(i);
        }

        private void cboSpcMod_SelectedIndexChanged(object sender, EventArgs e)
        {
            IList<etyFrtAgyBns> ilSrc = srcBinding.DataSource as IList<etyFrtAgyBns>;
            if (ilSrc == null || ilSrc.Count < 1)
                return;
            foreach (etyFrtAgyBns ety in ilSrc)
            {
                string spcMod = cboSpcMod.Value;
                ety.BNS_SPC_MOD = spcMod;
                if (string.IsNullOrWhiteSpace(spcMod) || spcMod == "***")
                    ety.BNS_SPC_MOD = "";
                else
                    ety.BNS_SPC_MOD_DESC = global.ilBnsSpcMod.First<etyCodeRef>(ey => { return ey.CODE == ety.BNS_SPC_MOD; }).CODE_DESC;
            }
            for (int i = 0; i < ilSrc.Count; i++)
                srcBinding.ResetItem(i);

        }

        private void cboClientName_EditValueChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(cboClientName.Text)) return;
            cboClient_Id.Text =
            global.ilClient.First<etyClient>(ey => { return ey.CLIENT_NAM == cboClientName.Text; }).CLIENT_ID;
            cboClient_Id.GetCodeText();
        }

        private void txtClient_Contact_EditValueChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtClient_Contact.Text)) return;
            try
            {
                cboClient_Id.Text =
                global.ilClient.First<etyClient>(ey => { return ey.CLIENT_CONTACT == txtClient_Contact.Text; }).CLIENT_ID;
                cboClient_Id.GetCodeText();
            }
            catch
            { }
        }

        private void cLabel8_DoubleClick(object sender, EventArgs e)
        {
            if (TT.HelpInfo.MsgBox.ShowQuestionBox("是否添加窗口权限？\n\r建议系统管理员执行"))
            {
                TT.HelpInfo.MsgBox.ShowSuccessFailBox(
                global.bzUser.CreateFormSecrity(this, barManager1.Items, global.basSysPara.UserID, this.MOD_ID)   );
            }
        }

        private void lbCustomer_Id_DoubleClick(object sender, EventArgs e)
        {
            frmTest fm = new frmTest();
            fm.Show();
        }

        private void tbarBillDelete_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            //bzAgyBns.Delete_AgyBnsDoc(
            if (string.IsNullOrWhiteSpace(txtContract_No.Text) || ilChrg.Count<=0)
                return ;

            etyFrtAgyBns eyFabCon = srcBinding.Current as etyFrtAgyBns;
            eyFabCon.CONTRACT_NO = txtContract_No.Text;
            eyFabCon.CANCEL_NAM = global.basSysPara.UserID;
            eyFabCon.LST_MOD = "FRTBNS";
            eyFabCon.PORT_CODE = global.basSysPara.PORT_CODE;
            foreach (etyChargeDtl ey in (from dt in ilChrg
                                    where dt.INVOICE_NO !=""
                                    select dt))
            {
                eyFabCon.INVOICE_NO = ey.INVOICE_NO;
                break;
            }
            eyFabCon.CHARGE_NO = ilChrg[0].CHARGE_NO;

            bool success;
            if (TT.HelpInfo.MsgBox.ShowQuestionBox(string.Format("是否删除此业务单所计算费用：{0}？", new string[] { txtContract_No.Text })))
            {
                success = bzAgyBns.Delete_Billing_Result(eyFabCon);
                if (success)
                {
                    TT.HelpInfo.MsgBox.ShowSuccessBox("删除成功");
                    Billing(false);
                }
                else
                    TT.HelpInfo.MsgBox.ShowSuccessBox("删除失败");
            }
        }

        private void barViewBill_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            eyBillRq.BILL_KEY1 = eyBnsHdr.FABC_GKEY;
            eyBillRq.BILL_KEY2 = eyBnsHdr.CONTRACT_NO;
            eyBillRq.CUSTOMER = eyBnsHdr.CUSTOMER_ID;

            if (ilChrg.Count <= 0)
            {
                etyChargeDtl ey = new etyChargeDtl();
                ilChrg.Add(ey);
            }

            frmAgyBnsBillMain fmBill = new frmAgyBnsBillMain(ilChrg, eyBillRq, type_view_bill.ViewBnsAllBill, null, bzBill);
            fmBill.ShowDialog();
            Billing(false);
        }

        #region 锁单处理

        private void barUpLock_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (string.IsNullOrWhiteSpace(txtContract_No.Text))
                return;

            if (TT.HelpInfo.MsgBox.ShowQuestionBox(string.Format("是否处理业务单：{0}？", new string[] { txtContract_No.Text })))
            {
                try { splashScreenManager1.ShowWaitForm(); }
                catch { }
                etyFrtAgyBnsDoc eyDoc = new etyFrtAgyBnsDoc();
                eyDoc.CONTRACT_NO = txtContract_No.Text;
                eyDoc.BNS_STATUS = barUpLock.Tag.ToString();
                eyDoc.UPDATE_NAM = global.basSysPara.UserID;
                bool success = bzAgyBns.Lock_AgyBnsDoc(eyDoc);
                if (success)
                {
                    TT.HelpInfo.MsgBox.ShowSuccessBox("保存成功");
                    if (bnsStatus == "N")
                        bnsStatus = "A";
                    else
                        bnsStatus = "N";
                }
                else
                    TT.HelpInfo.MsgBox.ShowSuccessBox("保存失败");

                try { splashScreenManager1.CloseWaitForm(); }
                catch { }
            }

        }

        string _bnsStats = "N";
        private string bnsStatus
        {
            set
            {
                _bnsStats = value;
                if (_bnsStats == "N")                //解锁状态
                {
                    //有效
                    barDownLock.Visibility = DevExpress.XtraBars.BarItemVisibility.Never;
                    barUpLock.Tag = "A";
                    barUpLock.ImageIndex = 30;
                    barUpLock.Caption = "开锁状态";
                    tbarSave.Enabled = tbarDelete.Enabled = tbarBillDelete.Enabled = tbarCacula.Enabled = true;
                }
                else
                {
                    //禁用
                    barDownLock.Visibility = DevExpress.XtraBars.BarItemVisibility.Always;
                    barUpLock.Tag = "N";
                    barUpLock.ImageIndex = 29;
                    barUpLock.Caption = "锁单状态";
                    tbarSave.Enabled = tbarSaveBill.Enabled = tbarDelete.Enabled 
                        = tbarBillDelete.Enabled = tbarCacula.Enabled = false;
                    if (_bnsStats == "D")
                    {
                        barUpLock.Enabled = false;
                        panelControl1.Enabled = false;
                        grpBns.Enabled = false;
                    }
                }
            }
            get
            {
                return _bnsStats;
            }
        }

        #endregion 
    }
}
